package com.example.backend.mapper;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;
import java.util.Collections;
import java.util.StringJoiner;

public class DingDanDetailMapperProvider {

    /**
     * 生成统计菜品销售数量的 SQL
     *
     * @param orderNumbers 订单编号列表
     * @return SQL 字符串
     */
    public String countDishSalesByOrderNumbersSQL(@Param("orderNumbers") List<String> orderNumbers) {
        // 使用 SQL 类构建动态 SQL
        return new SQL() {{
            SELECT("dish_name, SUM(num) AS total_count");
            FROM("dingdan_detail");
            // 动态生成 IN 子句
            if (orderNumbers != null && !orderNumbers.isEmpty()) {
                StringJoiner sj = new StringJoiner(",", "(", ")");
                for (int i = 0; i < orderNumbers.size(); i++) {
                    sj.add("#{orderNumbers[" + i + "]}");
                }
                WHERE("dingdan_num IN " + sj.toString());
            } else {
                // 如果列表为空，添加一个永远为 false 的条件，避免语法错误
                WHERE("1 = 0");
            }
            GROUP_BY("dish_name");
        }}.toString();
    }

    /**
     * 生成计算总收入的 SQL
     *
     * @param orderNumbers 订单编号列表
     * @return SQL 字符串
     */
    public String calculateTotalIncomeByOrderNumbersSQL(@Param("orderNumbers") List<String> orderNumbers) {
        // 使用 SQL 类构建动态 SQL
        return new SQL() {{
            SELECT("SUM(money) AS total_income");
            FROM("dingdan");
            // 动态生成 IN 子句
            if (orderNumbers != null && !orderNumbers.isEmpty()) {
                StringJoiner sj = new StringJoiner(",", "(", ")");
                for (int i = 0; i < orderNumbers.size(); i++) {
                    sj.add("#{orderNumbers[" + i + "]}");
                }
                WHERE("dingdan_num IN " + sj.toString());
            } else {
                // 如果列表为空，添加一个永远为 false 的条件，避免语法错误
                WHERE("1 = 0");
            }
        }}.toString();
    }
}
